package com.moyu.shopapp.service.impl;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.moyu.shopapp.entity.Order;
import com.moyu.shopapp.service.AlipayService;
import com.moyu.shopapp.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AlipayServiceImpl implements AlipayService {

    @Autowired
    private OrderService orderService;

    Logger log = LoggerFactory.getLogger(AlipayServiceImpl.class);

    @Value("${alipay.returnUrl}")
    private String returnUrl;

    /**
     * web端订单支付
     *
     * @param outTradeNo  订单编号（唯一）
     * @param totalAmount 订单价格
     * @param subject     商品名称
     */
    @Override
    public String webPagePay(String subject, String outTradeNo, String totalAmount) {
        try {
            AlipayTradePagePayResponse response = Factory.Payment.Page().pay(subject, outTradeNo, totalAmount, returnUrl);
            if (ResponseChecker.success(response)) {
                log.info("调用成功");
                return response.getBody();
            } else {
                log.error("调用失败，原因" + response.getBody());
            }
        } catch (Exception e) {
            log.error("调用发生异常，原因" + e.getMessage());
        }
        return null;
    }

    /**
     * 支付异步回调 将异步通知中收到的所有参数都存放到map中
     *
     * @param request
     * @return
     */
    @Override
    public String notifyUrl(HttpServletRequest request) {
        Map<String, String> map = new HashMap();
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String key = parameterNames.nextElement();
            String value = request.getParameter(key);
            map.put(key, value);
        }
        //验签
        try {
            if (Factory.Payment.Common().verifyNotify(map)) {
                log.info("异步通知验签通过");
                //验证用户的支付结果
                String trade_status = request.getParameter("trade_status");
                if (trade_status.equals("TRADE_SUCCESS")) {
                    log.info("支付交易成功");
                    //TODO 更新订单支付状态.....
                    LambdaUpdateWrapper<Order> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.set(Order::getPaymentStatus,"success")
                                    .eq(Order::getOrderId,map.get("out_trade_no"));
                    orderService.update(null,updateWrapper);
                }
            } else {
                log.error("异步通知验签失败");
                return "fail";
            }
        } catch (Exception e) {
            log.error("异步发生异常{}", e.getMessage());
            return "fail";
        }
        return "success";
    }

    /**
     * 支付同步步回调
     *
     * @param request
     * @return
     */
    @Override
    public Map<String, String[]> returnUrl(HttpServletRequest request) {
        return request.getParameterMap();
    }

}
